package com.project;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class CustomerRealm extends AuthorizingRealm {

    public CustomerRealm() {
        //创建凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密算法
        matcher.setHashAlgorithmName("md5");
        //设置散列次数
        matcher.setHashIterations(512);
        //为true时表示用加密的hex编码，为false时表示用Base64编码
        matcher.setStoredCredentialsHexEncoded(true);
        //将realm设置凭证管理
        this.setCredentialsMatcher(matcher);
    }

    /**
     * 用于授权方法，
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到主体的名称，也就是用户名
        String userName = principalCollection.getPrimaryPrincipal().toString();

        if ("tom".equals(userName)){
            //创建授权集合
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            //给用户授予角色集合，授权后，该用户拥有这些角色对应的权限
            authorizationInfo.addRoles(List.of("customer","manager","order"));
            //给用户授予指定的权限
            authorizationInfo.addStringPermission("user:create");
            authorizationInfo.addStringPermission("order:*");
            return authorizationInfo;
        }
        return null;
    }



    /**
     *  //专门用于认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //得到登录主体的用户名
        String userName = authenticationToken.getPrincipal().toString();
       if ("tom".equals(userName)){
           //返回认证对象，第一个参数为主体，第二个参数为密码，第三个参数为realm名称
           return new SimpleAuthenticationInfo(userName,"c8c1b15d5648cd55892cc2dbd0327807",
                   ByteSource.Util.bytes("hsy".getBytes()),this.getName());
       }



        return null;
    }
}
